package cn.tedu._08security.base.config;

import cn.tedu._08security.service.UserDetailsServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.SecurityFilterChain;

import static org.springframework.security.config.Customizer.withDefaults;

//启用鉴权功能
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
public class SecurityConfig {
    /**
     * 创建UserDetailsService对象，放到Spring Ioc容器中
     * 用于调用loadUserByUsername方法
     */
    @Bean
    public UserDetailsService userDetailsService() {
        return new UserDetailsServiceImpl();
    }
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(authorize -> authorize
                //设置 /api/public/** 不需要认证
                .requestMatchers("/api/public/**").permitAll()
                //其他请求需要认证
                .anyRequest().authenticated()
        )
        //表单登录的相关请求不需要认证
        .formLogin(form -> form.permitAll());
        return http.build();
    }
}
